package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ExcelDictDTOListener
 * @Description TODO
 * @Author ZengRj
 * @Date 2022/8/25 23:48
 * @Version 1.0
 */

@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    //每隔5条存储数据库
    private static final int BATCH_COUNT = 5;

    List<ExcelDictDTO> excelDictDTOList = new ArrayList<>();

    private DictMapper dictMapper;

    //传入mapper对象
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    /**
     * 遍历每一行的记录
     * @param excelDictDTO
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", excelDictDTO);
        excelDictDTOList.add(excelDictDTO);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(excelDictDTOList.size()==BATCH_COUNT){
            saveData();
            excelDictDTOList.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成");
    }

    /**
     * 存储数据库
     */
    private void saveData(){
        log.info("{}条数据，开始存储数据库!",excelDictDTOList.size());
        dictMapper.insertBatch(excelDictDTOList); //批量插入
        log.info("存储数据库成功！");
    }
}
